package com.qianfeng.openapi.search.service.impl;

import com.qianfeng.openapi.search.bean.TableData;
import com.qianfeng.openapi.search.service.CustomerSearchService;
import com.qianfeng.openapi.search.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class CustomerSearchServiceImpl implements CustomerSearchService {

    @Resource
    private RestHighLevelClient client;

    @Value("${elasticsearch.customer.index}")
    private String index;

    @Value("${elasticsearch.customer.type}")
    private String type;

    @Override
    public String findCustomerByNickNameAndStateByPage(Map parameter) throws IOException {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //1. 创建request
        SearchRequest request = new SearchRequest();

        //2. 封装request
        request.indices(index);
        request.types(type);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 封装nickname
        Object nickname = parameter.get("nickname");
        if(!StringUtils.isEmpty(nickname)){
            boolQuery.must(QueryBuilders.matchQuery("nickname",nickname));
        }
        // 封装state
        Object state = parameter.get("state");
        if(state != null){
            boolQuery.must(QueryBuilders.termQuery("state",state));
        }
        sourceBuilder.query(boolQuery);
        // 分页
        int page = (int) parameter.get("page");
        int limit = (int) parameter.get("limit");
        sourceBuilder.from((page - 1) * limit);
        sourceBuilder.size(limit);
        // 设置到request
        request.source(sourceBuilder);

        //3. 查询数据
        SearchResponse resp = client.search(request, RequestOptions.DEFAULT);
        //4. 封装结果
        TableData tableData = new TableData();
        tableData.setCount(resp.getHits().getTotalHits());
        List data = new ArrayList<>();
        for (SearchHit hit : resp.getHits().getHits()) {
            Map<String, Object> map = hit.getSourceAsMap();
            map.put("id",hit.getId());
            data.add(map);
        }
        tableData.setData(data);
        //5. 返回
        return JsonUtil.getJSON(tableData);
    }

    @Override
    public void add(Map parameter) throws IOException {
        //1.
        IndexRequest request = new IndexRequest(index,type,parameter.get("id") + "");
        //2.
        request.source(parameter);
        //3.
        IndexResponse resp = client.index(request, RequestOptions.DEFAULT);
        //4.
        if(!"created".equalsIgnoreCase(resp.getResult().toString())){
            log.error("【搜索模块】 添加客户信息失败  ， customer = {}",parameter);
            throw new RuntimeException("【搜索模块】 添加客户信息失败 ");
        }
    }
}
